package com.example.takeaway.controller;



import cn.hutool.core.collection.CollUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.takeaway.common.R;
import com.example.takeaway.entity.User;
import com.example.takeaway.service.UserService;
import com.example.takeaway.utils.SMSUtils;
import com.example.takeaway.utils.ValidateCodeUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
@AllArgsConstructor
public class UserController {

    private final UserService userService;
    private final RedisTemplate redisTemplate;


    /**
     * 发送验证码请求
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession httpSession , @RequestBody  User user) throws Exception {

        //1.获取手机号
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)) {

            //2.随机生成四位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("验证码是：{}",code);

            //把验证吧通过阿里云的Api接口发送给手机
             SMSUtils.createClient("LTAI5tDzR3JKbfxxVA1JBUkA", "cLYw6wYP7HKKzCDxz7uvUb5mFXmtzV");
             SMSUtils.sendSms(phone , code);


            //需要将生成的验证码保存到session中
//            httpSession.setAttribute(phone,code);
            //将我们生成的验证码保存到redis当中 并且设置有效期5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);



            return R.success("手机验证码短信发送成功");

        }


        return R.error("短信发送失败");
    }


    /**
     * 登录
     * @param httpSession
     * @param map
     * @return
     */

    @PostMapping("/login")
    public R<User> login(HttpSession httpSession , @RequestBody Map map){

        log.info(map.toString());

        //获取手机号
        String phone = map.get("phone").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从redis中去验证码
        Object codeRedis = redisTemplate.opsForValue().get(phone);

        //从Session中获取保存的验证码
//        Object codeInSession = httpSession.getAttribute(phone);
//        log.info("Session里面的code：{}",codeInSession);


        //校验验证码
        if(codeRedis != null && codeRedis.equals(code)){
            log.info("验证成功");

            //如果能比对成功 说明登录成功
            //判断用户是否为新用户 如果是新用户 自动完成注册

            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);

            User user = userService.getOne(wrapper);

            if(user == null){

                user = new User();
                user.setPhone(phone);
                user.setStatus(1);

                userService.save(user);

            }
                httpSession.setAttribute("user",user.getId());

                //如果用户登录成功 删除redis缓存的验证码
                redisTemplate.delete(phone);

                return R.success(user);
        }




        return R.error("验证码输入错误");
    }




}
